﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;
using WeddingEventManagement_API;
using WeddingEventManagementApp.Models;

namespace WeddingEventManagementApp.Controllers
{
    public class SearchController : BaseController
    {
        //
        // GET: /Search/?term={query}

        public JsonResult Index(string term)
        {
            QueryManager qm = new QueryManager();
            var x = qm.AutoSearch(term, 3);
            const string gravatarText = "<img src='http://www.gravatar.com/avatar/{0}?s={1}&d=identicon'/>";

            List<Search_VM> data = (from d in x.Clients
                select new Search_VM()
                {
                    Text = d.FirstName + " " + d.LastName,
                    SubText = d.Email.ToLower(),
                    Link = Url.Action("Details", "Client", new { id = d.ClientID } ),
                    Image = string.Format( gravatarText, Utility.MD5Hash(d.Email.ToLower().Trim()), 40),
                    Category = "Client"
                })
                .ToList();

            data.AddRange(from d in x.Events
                select new Search_VM()
                {
                    Text = d.Title,
                    SubText = d.StartDate.ToLocalTime().ToString("MMMM dd, h:mm tt"),
                    Link = Url.Action("Details", "Event", new { id = d.EventID } ),
                    Image = "<i class='icon-calendar'></i> ",
                    Category = "Event"
                });

            data.AddRange(from d in x.Locations
                select new Search_VM()
                {
                    Text = d.Name,
                    SubText = d.City,
                    Link = Url.Action("Details", "Location", new { id = d.LocationID }),
                    Image = "<i class='icon-location'></i> ",
                    Category = "Location"
                });

            return Json(data, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Results(string q)
        {
            QueryManager qm = new QueryManager();
            var model = qm.AutoSearch(q);
            ViewBag.Query = q;
            return View(model);
        }

    }
}
